﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Emporium_Web.Controls;
using System.Web.UI.WebControls;
using Emporium_Web.DBML;

namespace Emporium_Web
{
    public partial class TelaSearch : System.Web.UI.UserControl
    {
        public event EventHandler Seleccionado;

        protected virtual void OnSeleccionado(EventArgs e)
        {
            if (Seleccionado != null)
                Seleccionado(this, e);
        }

        public string SortExpression
        {
            get
            {
                return ViewState["gv_SortExpression"] == null ? "" : ViewState["gv_SortExpression"].ToString();
            }
            set
            {
                ViewState["gv_SortExpression"] = value;
            }
        }

        public string SortDirection
        {
            get
            {
                return ViewState["gv_SortDirection"] == null ? "" : ViewState["gv_SortDirection"].ToString();
            }
            set
            {
                ViewState["gv_SortDirection"] = value;
            }
        }

        public int CodigoSeleccionado
        {
            get
            {
                return ViewState["CodigoSeleccionado"] == null ? 0 : Convert.ToInt32(ViewState["CodigoSeleccionado"]);
            }
            set
            {
                ViewState["CodigoSeleccionado"] = value;
            }
        }

        public string DescripcionSeleccionado
        {
            get
            {
                return ViewState["DescripcionSeleccionado"] == null ? "" : ViewState["DescripcionSeleccionado"].ToString();
            }
            set
            {
                ViewState["DescripcionSeleccionado"] = value;
                txtTela.Text = value;
            }
        }

        public bool Enabled
        {
            set
            {
                txtTela.Enabled = value;
                btnMostrarModal.Visible = value;
            }
        }

        public bool EnabledTextBox
        {
            set
            {
                txtTela.Enabled = value;
            }
        }

        protected string _validationGroup;
        public string ValidationGroup
        {
            get
            {
                return _validationGroup;
            }
            set
            {
                _validationGroup = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            warningMessage.Visible = false;
            errorMessage.Visible = false;
            EstablecerValidaciones(!string.IsNullOrEmpty(ValidationGroup));
        }

        public void Mostrar()
        {
            mpeBusquedaTela.Show();
        }

        private void EstablecerValidaciones(bool blnValidation)
        {
            reqDescripcion.Enabled = blnValidation;
            reqDescripcion.ValidationGroup = ValidationGroup;
            reqDescripcion.ErrorMessage = Resources.MensajesValidacion.RequiredField;
        }

        protected void btnAceptar_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvTelas.Rows.Count; i++)
            {
                if ((int)gvTelas.DataKeys[i][0] == Convert.ToInt32(hdnSeleccion.Value))
                {
                    CodigoSeleccionado = Convert.ToInt32(hdnSeleccion.Value);
                    DescripcionSeleccionado = gvTelas.DataKeys[i][1].ToString();
                    txtTela.Text = DescripcionSeleccionado;

                    OnSeleccionado(e);
                    return;
                }
            }
        }

        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                ListarTelas();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }



        protected void gvPagerPageChanged(object sender, DataNavigatorEventArgs e)
        {
            try
            {
                ListarTelas();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void gvTelas_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (this.SortExpression != null && this.SortExpression.Equals(e.SortExpression))
                {
                    this.SortDirection = this.SortDirection.ToUpper().Equals("ASC") ? "DES" : "ASC";
                }
                else
                {
                    this.SortDirection = e.SortDirection.ToString().Substring(0, 3);
                }

                this.SortExpression = e.SortExpression;

                ListarTelas();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void gvTelas_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (gvTelas.HeaderRow == null)
                {
                    return;
                }

                this.SortExpression = e.CommandArgument != null ? e.CommandArgument.ToString() : "Id";
                this.SortDirection = e.CommandName.Equals("SortUp") ? "ASC" : "DES";

                ListarTelas();

            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        private void ActivaIconoOrdenamiento()
        {
            if (gvTelas.HeaderRow == null)
            {
                return;
            }

            if (this.SortDirection != null && this.SortDirection.ToUpper().Equals("ASC"))
            {
                LinkButton lnkSender = (LinkButton)gvTelas.HeaderRow.FindControl("lnkSortUp" + this.SortExpression);
                LinkButton lnkSortDown = (LinkButton)gvTelas.HeaderRow.FindControl(lnkSender.ID.Replace("SortUp", "SortDown"));
                lnkSortDown.CssClass = "sort-down";
                lnkSender.CssClass = "sort-up active";
            }
            else
            {
                LinkButton lnkSender = (LinkButton)gvTelas.HeaderRow.FindControl("lnkSortDown" + this.SortExpression);
                LinkButton lnkSortUp = (LinkButton)gvTelas.HeaderRow.FindControl(lnkSender.ID.Replace("SortDown", "SortUp"));
                lnkSortUp.CssClass = "sort-up";
                lnkSender.CssClass = "sort-down active";
            }
        }

        private void ListarTelas()
        {
            TablasDataContext database = new TablasDataContext();

            var listarQuery = from Telas in database.TG_Tela
                              where (txtDescripcion.Text.Trim() == "" || Telas.Tela_Descripcion.Contains(txtDescripcion.Text.Trim()))
                              select Telas;

            listarQuery = OrdenarQuery(listarQuery);

            foreach (var item in listarQuery)
            {
                
            }

            gvTelas.DataSource = listarQuery.Skip((gvPager.CurrentPage - 1) * gvPager.PageSize).Take(gvPager.PageSize).ToList();
            gvTelas.DataBind();

            int totalReg = listarQuery.Count();

            if (totalReg > 0)
            {
                gvTelas.UseAccessibleHeader = false;
                gvTelas.HeaderRow.TableSection = TableRowSection.TableHeader;
                gvPager.Visible = true;
                gvPager.TotalRowCount = totalReg;
                warningMessage.Visible = false;
            }
            else
            {
                lblWarningMessage.Text = Resources.MensajesValidacion.NoDataFound;
                warningMessage.Visible = true;
                gvPager.Visible = false;
            }

            lblMensajeGridFooter.Text = String.Format(Resources.MensajesValidacion.GridFooterMessage, totalReg);
            ActivaIconoOrdenamiento();

            mpeBusquedaTela.Show();
        }

        private IQueryable<TG_Tela> OrdenarQuery(IQueryable<TG_Tela> listarQuery)
        {
            if (this.SortExpression == null || this.SortExpression.Trim().Equals(""))
            {
                this.SortExpression = "Id";
            }

            if (this.SortDirection == null || this.SortDirection.Trim().Equals(""))
            {
                this.SortDirection = "DES";
            }

            if (this.SortExpression == "Id")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Tela_Id);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Tela_Id);
                }
            }
            else if (this.SortExpression == "Descripcion")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Tela_Descripcion);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Tela_Descripcion);
                }
            }

            return listarQuery;
        }


        protected void btnMostrarModal_Click(object sender, EventArgs e)
        {
            ListarTelas();
        }
    }
}